<template>
 <view>
  <u-upload
    ref="upload"
    :fileList="fileList1"
    @afterRead="afterRead"
    @delete="deletePic"
    :maxCount="1"
    :maxSize="5 * 1024 * 1024"
    width="250"
    height="150"
    :action='action'
  >
    <image :src="srcOrigin" :style='{width: styleSheet.width, height: styleSheet.height, borderRadius: styleSheet.borderRadius, overflow: styleSheet.overflow}'></image>
  </u-upload>
 </view>
</template>

<script>
// todo 上传组件 uView2.x 文档及功能不完善
import { authOssToken, userAvatarUpdate } from '@/config/api'
let _this = {}; // 如果小程序中this丢失的话，可以在外面定义，在生命周期中赋值
export default {
  props: {
    srcOrigin: {
      type: String,
      default: ''
    },
    styleSheet: {
      type: Object,
      default: () => {}
    }
  },
  data() {
   return {
    action: 'http:/laravel_shop_api.luwnto.oss-cn-beijing.aliyuncs.com/',
    fileList1: [],
    formData: {},
    upFileName: ''
   }
  },
  created() {
    _this = this
  },
  methods: {
    // 删除图片
    deletePic(event) {
      // this[`fileList${event.name}`].splice(event.index, 1)
    },
    // 新增图片
    async afterRead(event) {
      console.log(_this.fileList)
      console.log(event)
      // 请求API，获取oss token
      const ossToken = await authOssToken()
      // 设置上传域名
      _this.action = ossToken.host;
      // 处理唯一文件名
      /*
      const {file} = list[0]
      // #ifdef H5
      const fileName = file.name
      // #endif

      // #ifdef H5
      const fileName = file.path
      // #endif

      const suffix = fileName.slice(fileName.lastIndexOf('.'))
      const upFileName = _this.$u.guid(20) + suffix
      _this.upFileName = upFileName
      */
      // 额外的上传参数
      _this.formData = {
        'key': _this.upFileName, // 上传后的文件名 upFileName
        'policy': ossToken.policy,
        'OSSAccessKeyId': ossToken.accessid, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'signature': ossToken.signature,
      }

      _this.uploadFilePromise(event.file.url)
    },
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: _this.action,
          filePath: url,
          name: 'file',
          formData: _this.formData,
          success: (res) => {
            setTimeout(() => {
              resolve(res.data.data)
            }, 1000)
          }
        });
      })
    },
    async onSuccess() {
      // 请求API更新头像
      const res = await userAvatarUpdate({avatar: this.upFileName})
      this.$u.utils.updateUser()
      // 更新缓存的用户信息
      this.$u.toast('更新成功')
    }
  }
}
</script>

<style scoped>
</style>